import Ember from 'ember';

export default Ember.Route.extend({

  beforeModel: function(transition){
    console.log("transition.queryParams in",transition.queryParams);
  },
  model(params) {
    console.log("params in",params);
    var customerid = params.customer_id;
    var customer = this.getCustomer(customerid);
    var workorderList = this.getWorkorderList(customer);
    var model = new Ember.RSVP.hash({customer:customer,workorderList:workorderList});
    return model;
  },
  getCustomer:function (customerid) {
    return  this.store.findRecord("customer", customerid);
  },
  getWorkorderList: function (customerPromise) {
    var _self = this;
    return new Ember.RSVP.Promise(function (resolve, reject) {
      customerPromise.then(function (customer) {
        console.log("customerPromise in,customer", customer);
        var workorderList = Ember.A();
        if (!customer) {
          resolve();
          return;
        }
        _self.store.query("workorder", {filter: {customer: customer.id}}).then(function (workorders) {
          console.log("workorders in", workorders);
          var index = 0;
          var len = workorders.get("length");
          workorders.forEach(function(workorder){
            workorderList.push(workorder);
            index++;
            if(index>=len){
              resolve(workorderList);
            }
          });
        });
      });
    });
  },
});
